package com.study.handler;

import com.study.model.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;
@Slf4j
public class UserServerHandler extends ChannelInboundHandlerAdapter {
    private ApplicationContext applicationContext;

    public UserServerHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = (RpcRequest) msg;
        Object result = null;
        try {
            String className = rpcRequest.getClassName();
            String methodName = rpcRequest.getMethodName();
            Class clazz = Class.forName(className);
            Object obj = applicationContext.getBean(clazz);

            Method method = clazz.getMethod(methodName, rpcRequest.getParameterTypes());
            result = method.invoke(obj, rpcRequest.getParameters());
        } catch (Exception e) {
            log.error("调用{}类的{}方法{}时发生错误，参数为{}，错误原因{}", rpcRequest.getClassName(),
                    rpcRequest.getMethodName(), rpcRequest.getParameters(), e.getMessage());
        } finally {
            ctx.writeAndFlush(result);
        }

    }
}
